package com.maodou.core.network

import okhttp3.Interceptor
import okhttp3.Response

/**
 * 认证失败拦截器：统一监听 401/403 响应码。
 * 命中后触发 [unauthorizedHandler] 回调（由 app 层实现清空登录态与跳转登录）。
 */
class UnauthorizedInterceptor(
    private val unauthorizedHandler: ((code: Int) -> Unit)?
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val code = response.code
        if (code == 401 || code == 403) {
            try {
                unauthorizedHandler?.invoke(code)
            } catch (_: Throwable) {
                // 避免回调异常影响网络请求流程
            }
        }
        return response
    }
}